package liuliu.throughwaring.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import net.tsz.afinal.annotation.view.CodeNote;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import liuliu.custom.control.edittext.ImageEditText;
import liuliu.custom.control.edittext.SpinnerEditText;
import liuliu.custom.control.toolbar.TToolbar;
import liuliu.custom.method.Utils;
import liuliu.throughwaring.R;
import liuliu.throughwaring.adapter.CommonAdapter;
import liuliu.throughwaring.adapter.ViewHolder;
import liuliu.throughwaring.base.BaseActivity;
import liuliu.throughwaring.control.add.police.company.IRegUnitView;
import liuliu.throughwaring.control.add.police.company.RegUnitListener;
import liuliu.custom.model.CodeModel;
import liuliu.throughwaring.model.CompanyModel;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by liuliu on 2015/11/19   9:25
 * 注册民警信息
 *
 * @author 柳伟杰
 * @Email 1031066280@qq.com
 */
public class RegUnitActivity extends BaseActivity implements IRegUnitView {
    @CodeNote(id = R.id.reg_unit_name)
    ImageEditText reg_unit_name;//单位名称
    @CodeNote(id = R.id.reg_unit_corporation)
    ImageEditText reg_unit_corporation;//单位法人
    @CodeNote(id = R.id.reg_unit_security)
    ImageEditText txt_reg_unit_securitytel;//治安负责
    @CodeNote(id = R.id.reg_unit_address)
    ImageEditText reg_unit_address;//单位地址
    @CodeNote(id = R.id.reg_unit_btn, click = "onClick")
    Button reg_btn;//注册
    @CodeNote(id = R.id.reg_unit_tel)
    ImageEditText reg_unit_tel;//电话
    @CodeNote(id = R.id.reg_unit_remark)
    ImageEditText reg_unit_remark;//备注
    @CodeNote(id = R.id.reg_unit_img, click = "onClick")
    ImageView reg_unit_img;//单位照片
    CompanyModel companyModel = new CompanyModel();
    RegUnitListener mListener;
    @CodeNote(id = R.id.reg_unit_btn_add, click = "onClick")
    Button btnAdd;
    @CodeNote(id = R.id.reg_unit_type, click = "onClick")
    SpinnerEditText reg_unit_type;
    Bitmap bm = null;
    List<CodeModel> mCodeList;
    @CodeNote(id = R.id.right_menu_toolbar)
    TToolbar toolbar;
    @CodeNote(id = R.id.reg_unit_toolbar)
    TToolbar UnitToolbar;
    @CodeNote(id = R.id.right_menu_listview)
    ListView mRightMenu;
    //右侧菜单
    @CodeNote(id = R.id.reg_person_right_menu_draw)
    DrawerLayout right_menu;//右侧菜单
    CompanyModel unitModel = null;
    boolean isTOManager = false;

    @Override
    public void initViews() {
        setContentView(R.layout.activity_reg_unit);
        unitModel = (CompanyModel) getIntent().getSerializableExtra("UnitModel");
        if (unitModel != null) {
            isTOManager = true;
        }
        UnitToolbar.setCenterTitle("单位注册");
        companyModel.setCompanyType("Company");
        mListener = new RegUnitListener(this, this);
        reg_unit_address.setText(Utils.ReadString("NowLocation"));
    }

    @Override
    public void initEvents() {
        if (null != unitModel) {
            reg_unit_name.setText(Utils.URLEncode(unitModel.getCompanyName()));
            reg_unit_address.setText(unitModel.getCompanyAddress());
            reg_unit_remark.setText(Utils.URLEncode(unitModel.getCompanyComment()));
            txt_reg_unit_securitytel.setText(Utils.URLEncode(unitModel.getCompanySecurityPerson()));
            reg_unit_tel.setText(Utils.URLEncode(unitModel.getCompanyPhoneNumber()));
            reg_unit_corporation.setText(Utils.URLEncode(unitModel.getCompanyLegalPerson()));
            reg_unit_img.setImageResource(R.mipmap.main_add_img);
            reg_unit_type.setCenterTxt("行业场所");
        }
        toolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                drawerManager();
            }
        });
        mRightMenu.setVisibility(View.VISIBLE);
        setCodeList();
        //顶部菜单左侧点击
        UnitToolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                finish();
            }
        });
        reg_unit_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refushRightMenu();
                drawerManager();
            }
        });
    }

    private void setCodeList() {
        mCodeList = new ArrayList<>();
        CodeModel code = new CodeModel();
        code.setName("行业场所");
        code.setValue("行业场所");
        mCodeList.add(code);

        code = new CodeModel();
        code.setValue("娱乐场所");
        code.setName("娱乐场所");
        mCodeList.add(code);

        code = new CodeModel();
        code.setValue("企事业单位");
        code.setName("企事业单位");
        mCodeList.add(code);

        code = new CodeModel();
        code.setValue("重点单位");
        code.setName("重点单位");
        mCodeList.add(code);

        code = new CodeModel();
        code.setValue("其他");
        code.setName("其他");
        mCodeList.add(code);

    }

    private void refushRightMenu() {
        //左划菜单的Adapter
        mRightMenu.setAdapter(new CommonAdapter<CodeModel>(this, mCodeList,
                R.layout.right_menu_item) {
            @Override
            public void convert(final ViewHolder holder, final CodeModel model, int position) {
                if (model.getValue() != null) {
                    holder.setText(R.id.right_menu_title, model.getValue());
                }
            }
        });

        //左划菜单项点击事件
        mRightMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                drawerManager();
                reg_unit_type.setCenterTxt(mCodeList.get(position).getValue());
            }
        });
        //设置高度
        setListViewHeightBasedOnChildren(mRightMenu);
    }

    /*开启关闭左划菜单*/
    private void drawerManager() {
        if (right_menu.isDrawerOpen(GravityCompat.END)) {
            right_menu.closeDrawer(GravityCompat.END);
        } else {
            right_menu.openDrawer(GravityCompat.END);
            String title = "";
            title = "企业类型";
            toolbar.setCenterTitle(title);
        }
    }


    public static void setListViewHeightBasedOnChildren(ListView listView) {
        //获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) { //listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); //计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight() + listView.getDividerHeight() / 2; //统计所有子项+dividerheight的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() + 2)) + 120;
        //listView.getDividerHeight()获取子项间分隔符占用的高度
        //params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    //清空数据
    private void ClearText() {
        companyModel = new CompanyModel();
        reg_unit_name.setText("");
        reg_unit_address.setText("");
        reg_unit_remark.setText("");
        txt_reg_unit_securitytel.setText("");
        reg_unit_tel.setText("");
        reg_unit_corporation.setText("");
        reg_unit_img.setImageResource(R.mipmap.main_add_img);
        reg_unit_type.setCenterTxt("行业场所");
    }

    /**
     * 判断输入内容是否为空
     *
     * @return true，全部填写完成。false，有空内容
     */
    private boolean checkText() {
        if (reg_unit_name.getText().equals("")) {
            Utils.ToastShort(RegUnitActivity.this, "单位名称不能为空!");
            return false;
        }

        if (reg_unit_corporation.getText().equals("")) {
            Utils.ToastShort(RegUnitActivity.this, "单位法人不能为空!");
            return false;
        }
        if (txt_reg_unit_securitytel.getText().equals("")) {
            Utils.ToastShort(RegUnitActivity.this, "治安负责不能为空!");
            return false;
        }
        if (reg_unit_tel.getText().equals("")) {
            Utils.ToastShort(RegUnitActivity.this, "联系电话不能为空!");
            return false;
        }
        if (reg_unit_address.getText().equals("")) {
            Utils.ToastShort(RegUnitActivity.this, "单位地址不能为空!");
            return false;
        }
        if (bm == null) {
            Utils.ToastShort(RegUnitActivity.this, "请为单位拍照!");
            return false;
        }
        return true;

    }

    //获取页面数据
    private void getText() {
        if (unitModel != null) {
            companyModel.setCompanyId(unitModel.getCompanyId());
        }
        companyModel.setCompanyLegalPerson(reg_unit_corporation.getText());
        companyModel.setCompanyName(reg_unit_name.getText().trim());
        companyModel.setCompanyAddress(reg_unit_address.getText().trim());
        companyModel.setCompanyComment(reg_unit_remark.getText().trim());
        companyModel.setCompanySecurityPerson(txt_reg_unit_securitytel.getText().trim());
        companyModel.setCompanyPhoneNumber(reg_unit_tel.getText().trim());
        if (bm != null) {
            companyModel.setCompanyOveralImageUrl(mPath);
        }
    }


    boolean saveAndadd = false;//保存并添加，true.false只是保存
    private String mPath;

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.reg_unit_btn://保存按钮
                if (checkText()) {
                    getText();
                    companyModel.setIsPush("null");
                    mListener.RegUnit(companyModel);
                    saveAndadd = false;
                }
                break;
            case R.id.reg_unit_img:
                Intent intent = new Intent(RegUnitActivity.this, MultiImageSelectorActivity.class);
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);// 是否显示拍摄图片
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);// 最大可选择图片数量
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);// 选择模式
                intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mPath);// 默认选择
                startActivityForResult(intent, 110);
                break;
            case R.id.reg_unit_btn_add://保存并继续添加按钮
                if (checkText()) {
                    getText();
                    companyModel.setIsPush("null");
                    mListener.RegUnit(companyModel);
                    saveAndadd = false;
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 110) {
            if (resultCode == RESULT_OK) {
                mPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT).get(0);
                File file = new File(mPath);
                if (file.exists()) {
                    bm = BitmapFactory.decodeFile(mPath);
                    Log.i("bm:", "" + mPath);
                    if (bm != null) {
                        reg_unit_img.setImageBitmap(Utils.centerSquareScaleBitmap(bm, 60));
                    }
                }
            }
        }
    }

    @Override
    public void onRegUnitResult(boolean isTrue, String mes) {
        if (saveAndadd) {//停留在本页，只是清空数据。
            ClearText();
        } else if (isTOManager) {
            this.finish();
            mUtils.IntentPost(CompanyDetailActivity.class, new Utils.putListener() {
                @Override
                public void put(Intent intent) {//管理按钮,跳转到单位详细信息页面
                    intent.putExtra("CompanyId", unitModel.getCompanyId());
                }
            });
        } else {//返回查询页面。并显示查询结果。
            setResult(131, new Intent());
            this.finish();
        }

        mUtils.ToastShort("添加成功");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bm != null) {
            if (!bm.isRecycled()) {
                bm.recycle();//回收图片所占的内存
                System.gc();
            }
        }
    }
}
